<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-steps :active="active" finish-status="success">
      <el-step title="输入分组名称"></el-step>
      <el-step title="选择店铺"></el-step>
      <el-step title="选择酒店"></el-step>
    </el-steps>
    <el-form :model="dataForm" ref="dataForm" label-width="0px" style="width:100%">
      <!--请输入分组名称-->
      <el-form-item prop="groupName" v-if="active === 0" style="width:100%">
        <el-input v-model="dataForm.groupName" placeholder="请输入分组名称" style="width:100%"></el-input>
      </el-form-item>
      <!--选择店铺-->
      <el-form-item v-if="active === 1" prop="pfId" label label-width="0px">
        <el-select
          v-model="dataForm.pfId"
          @change="pfChange"
          placeholder="请选择销售平台"
          style="width:100%"
        >
          <el-option v-for="item in pfs" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="active === 1" prop="storId" label label-width="0px">
        <el-select v-model="dataForm.storId" placeholder="请选择店铺" style="width:100%">
          <el-option v-for="item in stores" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!--选择酒店-->
    <template v-if="active === 2">
      <el-tabs v-model="dataForm.groupType" type="border-card">
        <el-tab-pane name="1" label="选择指定条件酒店">
          <el-form ref="dfHotel" :inline="true" :model="dfHotel">
            <el-form-item>
              <el-select
                v-model="dfHotel.province"
                clearable
                @change="proChange"
                placeholder="请选择省份"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item.cityCode"
                  :label="item.cityNameZh"
                  :value="item.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="dfHotel.city" clearable @change="cityChange" placeholder="请选择城市">
                <el-option
                  v-for="item in citys"
                  :key="item.cityCode"
                  :label="item.cityNameZh"
                  :value="item.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="dfHotel.district" clearable placeholder="请选择区域">
                <el-option
                  v-for="item in districts"
                  :key="item.cityCode"
                  :label="item.cityNameZh"
                  :value="item.cityCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="dfHotel.brand" clearable placeholder="请选择品牌">
                <el-option
                  v-for="item in brands"
                  :key="item.id"
                  :label="item.bname"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane name="2" label="选择指定酒店">
          <el-row style="margin-bottom:10px;">
            <el-col :span="16">
              <el-input v-model="dataForm.hotelName" clearable placeholder="酒店名称"></el-input>
            </el-col>
            <el-col :span="7" style="margin-left:22px;">
              <el-button type="primary" @click="queryByName">查询</el-button>
              <el-button
                type="primary"
                @click="select"
                :disabled="dataListSelections.length <= 0"
              >添加</el-button>
            </el-col>
          </el-row>
          <el-table
            :data="dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%;"
          >
            <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
            <el-table-column prop="hotelName" header-align="center" align="center" label="酒店名称"></el-table-column>
            <el-table-column prop="address" header-align="center" align="center" label="酒店地址"></el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[5, 10]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper"
          ></el-pagination>
        </el-tab-pane>
        <el-tab-pane name="3" label="EXCEL上架酒店">
          <el-form :inline="true" :model="dataForm">
              <el-upload
                class="upload-demo"
                action=""
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :limit="limitUpload"
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                :auto-upload="false"
              >
                <el-button size="small" type="primary">点击导入酒店</el-button>
              </el-upload>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </template>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="prev" v-if="active != 0">上一步</el-button>
      <el-button type="primary" @click="next" v-if="active != 3">下一步</el-button>
      <el-button type="primary" @click="dataFormSubmit" v-if="active === 3">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils"
export default {
  data() {
    return {
      limitUpload: 1,
      visible: false,
      active: 0,
      dfHotel: {
        province: null,
        city: null,
        district: null,
        brand: null,
        hotelName: null
      },
      pfs: [],
      stores: [],
      tier: 1,
      parentId: -1,
      provinces: [],
      citys: [],
      districts: [],
      brands: [],
      dataForm: {
        id: 0,
        groupName: '',
        groupType: '1',
        dtId: '',
        pfId: null,
        storId: null,
        hotelName: '',
        hotelIds: []
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 5,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: []
    }
  },
  methods: {
    //上传文件时处理方法
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      this.importfxx(this.fileTemp);

    },
    //超出最大上传文件数量时的处理方法
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //移除文件的操作方法
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    importfxx(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据

      this.file = event.currentTarget.files[0];

      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;

      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          //此处引入，用于解析excel
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
          //此处可对数据进行处理
          let arr = [];
          outdata.map((v) => {
            arr.push(v["酒店id"]);
          });
          console.info(arr);
          _this.dataForm.hotelIds = arr;
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    // 选择销售平台获取销售平台下的店铺
    pfChange(value) {
      this.dataForm.storId = null
      this.$http({
        url: this.$http.adornUrl('/op/group/store'),
        method: 'get',
        params: this.$http.adornParams({
          'dtId': this.dataForm.dtId,
          "pf": this.dataForm.pfId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.stores = data.list
        } else {
          this.stores = []
        }
      })
    },
    prev() {
      this.active--
    },
    next() {
      // 第一步输入分组名称
      if (this.active === 0 && this.dataForm.groupName === '') {
        this.$alert('输入分组名称', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      // 第二步，选择店铺
      if (this.active === 1 && this.dataForm.storId === null) {
        this.$alert('请选择店铺', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }
      // 第三步，添加指定条件酒店
      if (this.active === 2 && this.dataForm.groupType === '1') {
        if (this.dfHotel.province === null && this.dfHotel.city === null && this.dfHotel.district === null && (this.dfHotel.brand === null || this.dfHotel.brand.length <= 0)) {
          this.$alert('请选择区域或品牌', '提示', {
            confirmButtonText: '确定',
            callback: action => {
            }
          })
          return
        }
      }
      // 第三步，添加指定酒店
      if (this.active === 2 && this.dataForm.groupType === '2') {
        if (this.dataForm.hotelIds.length <= 0 && this.dataListSelections.length <= 0) {
          this.$alert('请选酒店', '提示', {
            confirmButtonText: '确定',
            callback: action => {
            }
          })
          return
        }
      }
      if(this.dataForm.groupType === '3') {
        if (this.dataForm.hotelIds.length <= 0 || this.dataForm.hotelIds.length > 2000) {
          this.$alert('每次导入酒店数量0-2000', '提示', {
            confirmButtonText: '确定',
            callback: action => {}
          })
          return
        }
      }
      this.active++
    },
    // 获取区域查询条件
    getQuryCitys() {
      this.$http({
        url: this.$http.adornUrl('/op/group/citys'),
        method: 'post',
        params: this.$http.adornParams({
          tier: this.tier,
          parentId: this.parentId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          switch (this.tier) {
            case 1:
              this.provinces = data.list
              break
            case 2:
              this.citys = data.list
              break
            case 3:
              this.districts = data.list
              break
          }
        }
      })
    },
    // 选择省份
    proChange(value) {
      this.parentId = value
      this.tier = 2
      this.getQuryCitys()
    },
    // 选择城市
    cityChange(value) {
      this.parentId = value
      this.tier = 3
      this.getQuryCitys()
    },
    // 查询品牌
    getBrands() {
      this.$http({
        url: this.$http.adornUrl('/op/group/brand'),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.brands = data.list
        }
      })
    },
    // 获取指定的酒店（按酒店名称）
    getDataList() {
      this.dataListSelections = []
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/op/group/hotels'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'pf': this.dataForm.pfId,
          'store': this.dataForm.storId,
          'dtId': this.dataForm.dtId,
          'name': this.dataForm.hotelName
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    queryByName() {
      this.pageIndex = 1
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    select() {
      if (this.dataListSelections.length <= 0) {
        return
      }
      let ids = this.dataListSelections.map(item => {
        return item.hotelId
      })
      // 把选择的酒店添加到酒店列表
      this.dataForm.hotelIds = this.dataForm.hotelIds.concat(ids)
      // 去重
      this.dataForm.hotelIds = this.dataForm.hotelIds.filter((item, index) => {
        return this.dataForm.hotelIds.indexOf(item) === index
      });
      this.dataListSelections = []
    },
    init(id, dtId, pfs) {
      this.dataForm.id = id
      this.visible = true
      this.dataForm.hotelIds = []
      this.dataListSelections = []
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.dataForm.dtId = dtId
        this.dataForm.hotelIds = []
        this.pfs = pfs
        this.getQuryCitys()
        this.getBrands()
        this.active = 0
        //修改
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/op/group/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.groupName = data.group.groupName
              this.dataForm.dtId = data.group.dtId
              this.dataForm.pfId = data.group.blonPlantform
              this.pfChange(this.dataForm.pfId)
              this.dataForm.storId = data.group.storeId
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.select()
      this.$http({
        url: this.$http.adornUrl("/op/group/save/"),
        method: 'post',
        data: this.$http.adornData({
          'id': this.dataForm.id,
          'groupName': this.dataForm.groupName,
          'dtId': this.dataForm.dtId,
          'pf': this.dataForm.pfId,
          'storId': this.dataForm.storId,
          'groupType': this.dataForm.groupType,
          // 'province': this.dfHotel.province,
          'city': this.dfHotel.city,
          'county': this.dfHotel.county,
          'brand': this.dfHotel.brand,
          'hotelIds': this.dataForm.hotelIds
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: data.msg,
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.dataListSelections = []
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        } else {
          this.$message.error(data.msg)
        }
        this.dataForm.hotelIds = []
        this.dataListSelections = []
      })
    }
  }
}
</script>
